package com.hm.business.shorturl.controller;

import com.hm.business.shorturl.dto.LinkUrlReqDTO;
import com.hm.business.shorturl.dto.ShortUrlResDTO;
import com.hm.business.shorturl.service.ShortUrlService;
import com.hm.business.vo.ResultVO;
import com.hm.common.validate.DataCheckGroups;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
* @Description: 短链接Controller层
* @param
* @return 
* @throws
* @author Coder编程
* @date 2021/6/16 16:34
*/
@Slf4j
@RestController
public class ShortUrlController {

    @Autowired
    private ShortUrlService shortUrlService;

    /**
     * 生成短链
     * @param linkUrl
     * @return
     */
    @RequestMapping ("generateShortUrl")
    public ResultVO<ShortUrlResDTO> generateShortUrl(@RequestBody @Validated(value = DataCheckGroups.GenerateShortUrlValidate.class) LinkUrlReqDTO linkUrl) {
        ResultVO<ShortUrlResDTO> shortUrl;
        try {
            log.info("====》ShortUrlController.generateShortUrl.linUrl{}",linkUrl);
            shortUrl = shortUrlService.generateShortUrl(linkUrl);
        } catch (Exception e) {
            log.error("《####ShortUrlController.generateShortUrl.error",e);
            shortUrl = new ResultVO(500 ,"生成短链失败" + e.getMessage());
        }
        log.info("《====ShortUrlController.generateShortUrl.shortUrl{}",shortUrl);
        return shortUrl;
    }

    /**
     * 还原短链接至长网址
     * */
    @RequestMapping("/{shortUrl}")
    public void queryShortUrl(@PathVariable("shortUrl") String shortUrl, HttpServletResponse response) {
        ResultVO<String> longUrl = null;
        try {
            int minShortLen = 2;
            if (shortUrl.length() < minShortLen) {
                /* 短链长度不对 */
                return;
            }
            Integer dbShare = Integer.valueOf(shortUrl.substring(0, 1));
            String realShortUrl = shortUrl.substring(1);
            longUrl = shortUrlService.queryShortUrl(dbShare, realShortUrl);
            if (200 == longUrl.getCode()) {
                response.sendRedirect(longUrl.getData());
                return;
            }
        } catch (IOException e) {
            log.error("《####ShortUrlController.queryShortUrl.error",e);
        }
        return;
    }

}
